package de.g18.scavengerhunt.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

import com.google.android.maps.GeoPoint;

import de.g18.scavengerhunt.AppApplicationContext;

/**
 * Several methods used in the application
 */
public class GameUtils {

    private static String LOG_TAG = GameUtils.class.getSimpleName();

    /**
     * Calculates the distance (in meters) between two GeoPoints.
     * 
     * @param pointA
     * @param pointB
     * @return int the distance in meters
     */
    public static int getDistanceBetweenPoints(GeoPoint pointA, GeoPoint pointB) {
        int distance = 0;
        Location locationA = new Location(LocationManager.GPS_PROVIDER);
        locationA.setLatitude(pointA.getLatitudeE6() / 1E6);
        locationA.setLongitude(pointA.getLongitudeE6() / 1E6);
        Location locationB = new Location(LocationManager.GPS_PROVIDER);
        locationB.setLatitude(pointB.getLatitudeE6() / 1E6);
        locationB.setLongitude(pointB.getLongitudeE6() / 1E6);

        distance = (int) locationA.distanceTo(locationB);
        return distance;
    }

    /**
     * Copies an InputStream to an OutputStream.
     * 
     * @param is
     * @param os
     */
    public static void copyStream(InputStream is, OutputStream os) {
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Exception while copying stream " + e.getMessage());
        }
    }

    /**
     * Shows an activity
     * 
     * @param activity the activity to show
     */
    public static void showActivity(Activity activity) {
        Intent intent = new Intent(AppApplicationContext.getCurrentActivity().getApplicationContext(), activity.getClass());
        AppApplicationContext.getCurrentActivity().startActivity(intent);
        AppApplicationContext.getCurrentActivity().finish();

        // set current activity
        AppApplicationContext.setActivity(activity);
    }
}
